package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //删除当前菜品的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品分页查询
     **/
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //创建分页对象
        Page<Dish> pageinfo = new Page(page, pageSize);

        Page<DishDto> dishDtoPage = new Page<>();


        LambdaQueryWrapper<Dish> lqm = new LambdaQueryWrapper();
        lqm.like(name != null, Dish::getName, name);

        lqm.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        dishService.page(pageinfo, lqm);
// 拷贝 pageinfo 内的内容到 dishDtoPage
        BeanUtils.copyProperties(pageinfo, dishDtoPage, "records");

        //给 dishdtopage的 records 赋值
        List<Dish> records = pageinfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        //考虑到 修改菜品时候  有修改菜品所属分类的可能  删除菜品所属分类的所有菜品
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("修改菜品成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<String> ids) {

        log.info("ids:{}", ids);
        dishService.removeWithDishFlavor(ids);
        //删除redis内缓存的内容
        Set key = redisTemplate.keys("dish_");
        redisTemplate.delete(key);
        return R.success("菜品删除成功");

    }

    /**
     * 启停菜品
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        Dish dish = new Dish();
        dish.setStatus(status);
        // update dish set status=1 where id in(11111,222222)
        QueryWrapper<Dish> updateWrapper = new QueryWrapper<>();
        updateWrapper.in("id", ids);
        dishService.update(dish, updateWrapper);
        return R.success("更新菜品状态成功");
    }

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        log.info("{}", dish.toString());
        //先查询redis是否有缓存
        List<DishDto> dishDtolist = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        dishDtolist = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtolist != null) {
            //有缓存直接返回
            return R.success(dishDtolist);
        }


        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加菜品处于启售的条件
        lqw.eq(Dish::getStatus, 1);
        lqw.orderByAsc(Dish::getCreateTime).orderByAsc(Dish::getPrice);

        List<Dish> list = dishService.list(lqw);
        //现在返回的List中没有菜品所属分类Category  也没有菜品的口味信息 只存在菜品的基础信息  不满足需求
        //现在要实现 对菜品所属分类查询到
        //菜品口味信息返回
        dishDtolist = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将菜品的基础信息进行拷贝
            BeanUtils.copyProperties(item, dishDto);
            //实现菜品分类信息的填充
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //如果能够查询到的话
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //实现对菜品口味信息的填充
            //得到现在菜品的id
            Long dishid = item.getId();
            LambdaQueryWrapper<DishFlavor> lqw2 = new LambdaQueryWrapper<>();
            //填充查询条件 按照Dish的id来查询到其所有的口味信息
            lqw2.eq(DishFlavor::getDishId, dishid);

            List<DishFlavor> dishFlavors = dishFlavorService.list(lqw2);

            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        // key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //如果不存在   先查询数据库内   查询出内容将查询到的数据缓存  并设置时间
        redisTemplate.opsForValue().set(key, dishDtolist, 60, TimeUnit.MINUTES);

        return R.success(dishDtolist);
    }


}



